#include <windows.h>
#include <iostream>
#include <chrono>
#include <vector>
#include <d3d11.h>
#include <dxgi1_2.h>

// 导入dxgi_dup.cpp中定义的函数
extern "C" {
    __declspec(dllimport) int WINAPI DupInit(int outputIndex, int fps);
    __declspec(dllimport) void WINAPI DupShutdown();
    __declspec(dllimport) int WINAPI DupIsReady();
    __declspec(dllimport) unsigned int WINAPI DupGetPixel(int x, int y);
}

int main() {
    // 设置控制台输出UTF-8编码
    SetConsoleOutputCP(CP_UTF8);
    
    std::cout << "DXGI单点取色性能测试\n";
    std::cout << "====================\n";

    // 初始化屏幕捕获
    std::cout << "初始化屏幕捕获...\n";
    if (!DupInit(0, 60)) {
        std::cerr << "初始化失败\n";
        return -1;
    }

    // 等待捕获准备好
    std::cout << "等待捕获准备就绪...\n";
    int attempts = 0;
    while (!DupIsReady() && attempts < 100) {
        Sleep(50);
        attempts++;
    }

    if (!DupIsReady()) {
        std::cerr << "捕获未能准备就绪\n";
        DupShutdown();
        return -1;
    }

    std::cout << "开始性能测试...\n";

    // 测试参数
    const int testPoints[][2] = {
        {100, 100},
        {500, 300},
        {1000, 500},
        {1500, 800},
        {1920, 1080}
    };
    const int numTestPoints = sizeof(testPoints) / sizeof(testPoints[0]);
    const int iterations = 10000; // 总测试次数

    // 执行性能测试
    auto start = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < iterations; i++) {
        // 循环测试不同的点
        int x = testPoints[i % numTestPoints][0];
        int y = testPoints[i % numTestPoints][1];
        DupGetPixel(x, y);
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    double avgTime = (double)duration.count() / iterations;
    double opsPerSec = 1000000.0 / avgTime;

    std::cout << "测试结果:\n";
    std::cout << "总测试次数: " << iterations << "\n";
    std::cout << "总耗时: " << duration.count() << " 微秒\n";
    std::cout << "平均每次调用耗时: " << avgTime << " 微秒\n";
    std::cout << "每秒操作次数: " << opsPerSec << " 次/秒\n";

    // 测试不同坐标下的取色值
    std::cout << "\n各测试点颜色值:\n";
    for (int i = 0; i < numTestPoints; i++) {
        int x = testPoints[i][0];
        int y = testPoints[i][1];
        unsigned int color = DupGetPixel(x, y);
        std::cout << "坐标(" << x << ", " << y << ") 颜色值: 0x" 
                  << std::hex << color << std::dec << "\n";
    }

    // 关闭屏幕捕获
    DupShutdown();
    
    std::cout << "\n性能测试完成。\n";
    return 0;
}